package com.flow.asyncflow.web.controller;


import com.flow.asyncflow.core.entity.asyncFlowMonitor.AsyncFlowMonitorVo;
import com.flow.asyncflow.core.entity.asyncFlowMonitor.AsyncFlowOperatorEnumNameVo;
import com.flow.asyncflow.core.entity.asyncFlowMonitor.QueryAsyncFlowLogRequest;
import com.flow.asyncflow.core.entity.codegeneration.VelocityModel;
import com.flow.asyncflow.core.entity.codegeneration.VelocityRequest;
import com.flow.asyncflow.core.entity.mtdd.MTDD_GoJsModel;
import com.flow.asyncflow.core.entity.mtdd.MTDD_Model;
import com.flow.asyncflow.core.utils.mtdd.MTDD_Service;
import com.flow.asyncflow.core.utils.asyncFlowMonitor.AsyncFlowMonitor;
import com.flow.asyncflow.core.utils.codegeneration.AsyncFlowVelocity;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.MemberValuePair;
import com.github.javaparser.ast.expr.NormalAnnotationExpr;
import com.github.javaparser.ast.expr.StringLiteralExpr;

import com.github.javaparser.printer.PrettyPrinter;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/AsyncFlowAPI")
public class AsyncFlowAPIController {


    //region 异步流代码生成

    /**
     * 生成 异步流
     *
     * @param velocityRequest 请求
     * @return 返回
     */
    @SneakyThrows
    @PostMapping("codeGeneration")
    public String codeGeneration(@RequestBody VelocityRequest velocityRequest) {
        String result = "生成成功";
        //velocityRequest.setHasBaseContext(true);
        if (StringUtils.isBlank(velocityRequest.getAsyncFlowManagerName())) {
            result = "异步流模块英文名不能为空";
            return result;
        }
        if (StringUtils.isBlank(velocityRequest.getAsyncFlowManagerDes())) {
            result = "异步流中文描述不能为空";
            return result;
        }
        if (StringUtils.isBlank(velocityRequest.getAsyncFlowMaintainName())) {
            result = "异步流负责人";
            return result;
        }
        if (velocityRequest.getAsyncFlowTimeOutsLimit() <= 0) {
            result = "异步流超时时间必须大于0";
            return result;
        }
        velocityRequest.getAsyncFlowNodeInfoList().removeAll(velocityRequest.getAsyncFlowNodeInfoList().stream().filter(c -> StringUtils.isBlank(c.getAsyncFlowNodeFileName())).collect(Collectors.toList()));
        if (velocityRequest.getAsyncFlowNodeInfoList().isEmpty()) {
            result = "至少包含一个节点";
            return result;
        }
        AsyncFlowVelocity.buildAsyncFlowVelocity(velocityRequest);
        return result;

    }

    /**
     * 获取公共组件和管理器
     *
     * @return 返回
     */
    @SneakyThrows
    @PostMapping("loadPubNodeManager")
    public LinkedList<VelocityModel.AsyncFlowNodeInfo> loadPubNodeManager() {

        LinkedList<VelocityModel.AsyncFlowNodeInfo> pubAsyncFlowNodeInfoList;
        //String loadPubNodePackPath = basePackagePath + ".GetData.pubgetdata";
        //pubAsyncFlowNodeInfoList = AsyncFlowVelocity.loadNodeAndManager(ExecuteEnum.GetDataPub, loadPubNodePackPath);
        //String loadManagerPackPath = basePackagePath + ".Manager";
        //pubAsyncFlowNodeInfoList.addAll(AsyncFlowVelocity.loadNodeAndManager(ExecuteEnum.Manager, loadManagerPackPath));
        pubAsyncFlowNodeInfoList = AsyncFlowVelocity.loadNodeAndManagerV2();
        return pubAsyncFlowNodeInfoList;

    }

    /**
     * 获取管理器下面所有的节点
     *
     * @param asyncFlowModuleName 节点名称
     * @return 节点集合
     */
    @SneakyThrows
    @GetMapping("loadManagerNode")
    public VelocityRequest loadManagerNode(@RequestParam("asyncFlowManagerName") String asyncFlowModuleName,@RequestParam("operatorEnumName") String operatorEnumName) {

        return AsyncFlowVelocity.loadManagerNode(asyncFlowModuleName,operatorEnumName);

    }

    /**
     * 获取管理器下面所有的枚举
     *
     * @return 节点集合
     */
    @SneakyThrows
    @GetMapping("loadOperatorEnum")
    public List<VelocityModel.AsyncFlowOperatorEnumInfo> loadOperatorEnum(@RequestParam("asyncOldOperatorEnumName") String asyncOldOperatorEnumName) {

        return AsyncFlowVelocity.loadOperatorEnum(asyncOldOperatorEnumName);

    }
    //endregion

    //region 异步流监控

    /**
     * 查询 监控信息
     *
     * @param queryAsyncFlowLogRequest 请求
     * @return 返回
     */
    @SneakyThrows
    @PostMapping("getAsyncFlowLogByPage")
    public AsyncFlowMonitorVo getAsyncFlowLogByPage(@RequestBody QueryAsyncFlowLogRequest queryAsyncFlowLogRequest) {
        AsyncFlowMonitorVo asyncFlowMonitorVo = new AsyncFlowMonitorVo();
        if (queryAsyncFlowLogRequest.getStartDate() != null
                && queryAsyncFlowLogRequest.getEndDate() != null
                && queryAsyncFlowLogRequest.getStartDate().getMonthValue() != queryAsyncFlowLogRequest.getEndDate().getMonthValue()) {
            asyncFlowMonitorVo.setMsg("开始结束时间必须是同一个月");
            return asyncFlowMonitorVo;
        }
        if (queryAsyncFlowLogRequest.getStartDate() == null
                && queryAsyncFlowLogRequest.getEndDate() != null
                && queryAsyncFlowLogRequest.getEndDate().getMonthValue() > LocalDateTime.now().getMonthValue()) {
            asyncFlowMonitorVo.setMsg("开始时间不传，结束时间必须是当前月");
            return asyncFlowMonitorVo;
        }
        if (queryAsyncFlowLogRequest.getQueryType().equals("MongoDB")) {
            asyncFlowMonitorVo = new AsyncFlowMonitor().getAsyncFlowLogByPage(queryAsyncFlowLogRequest);
        } else {
            asyncFlowMonitorVo = new AsyncFlowMonitor().getAsyncFlowLogByPageEs(queryAsyncFlowLogRequest);
        }

        return asyncFlowMonitorVo;
    }

    /**
     * 查询 监控信息
     *
     * @return 返回
     */
    @SneakyThrows
    @PostMapping("getAsyncFlowNameList")
    public List<AsyncFlowOperatorEnumNameVo> getAsyncFlowNameList() {


        return new AsyncFlowMonitor().getAsyncFlowNameList();

    }

    //endregion

    //region 异步流站点视图

    /**
     * 加载异步流树形视图
     *
     * @return 项目视图JSON
     */
    @PostMapping("loadFlowTreeView")
    public MTDD_Model loadFlowTreeView() {

        return MTDD_Service.loadFlowTreeView();
    }

    /**
     * 新增项目模块信息
     *
     * @return
     */
    @GetMapping("addModuleInfo")
    @SneakyThrows
    public String addModuleInfo(@RequestParam("name") String name ,@RequestParam("des") String des) {

      return   MTDD_Service.addModuleInfo(name ,des);
    }

    /**
     * 新增项目模块信息
     *
     * @return
     */
    @GetMapping("editManagerModuleInfo")
    @SneakyThrows
    public String editManagerModuleInfo(@RequestParam("managerName") String managerName ,@RequestParam("managerModuleName") String managerModuleName,@RequestParam("managerModuleNameDes") String managerModuleNameDes) {

        return   MTDD_Service.editManagerModuleInfo(managerName ,managerModuleName,managerModuleNameDes);
    }

    /**
     * 获取节点GoJs信息
     *
     * @return
     */
    @GetMapping("loadFlowTreeNodeGoJsInfo")
    @SneakyThrows
    public MTDD_GoJsModel loadFlowTreeNodeGoJsInfo(@RequestParam("managerName") String managerName ,@RequestParam("managerModuleName") String managerModuleName) {

        MTDD_GoJsModel goJsModel = new MTDD_GoJsModel();
        goJsModel.setGoJsNodeEntityList(MTDD_Service.getAllNodes(managerName,managerModuleName));
        goJsModel.setGoJsLinkDataEntityList(MTDD_Service.loadNodeLinkArray(managerName,managerModuleName));
        return   goJsModel;
    }
    //endregion

    @RequestMapping("/test")
    @SneakyThrows
    public Object test() {

        Path path = Paths.get("/Users/list_dust/Documents/code/MyCode/asyncflow/src/main/java/com/flow/asyncflow/test/manager/asyncflowtest/PlusAsyncFlowTestManager.java");
        File file = path.toFile();
        //解析java文件生成AST
        CompilationUnit cu = StaticJavaParser.parse(file);
        List<AnnotationExpr> annotationNodes = cu.findAll(AnnotationExpr.class);
        for (AnnotationExpr annotation : annotationNodes) {

            if ("FlowInfo".equals(annotation.getName().toString())) {
                // 处理 @FlowInfo 注解的逻辑
                String s = annotation.getName().toString();
                //TODO 修改@FlowInfo 注解中的参数值
                if (annotation instanceof NormalAnnotationExpr) {
                    NormalAnnotationExpr normalAnnotationExpr = (NormalAnnotationExpr) annotation;
                    for (MemberValuePair pair : normalAnnotationExpr.getPairs()) {

                        if ("flowName".equals(pair.getName().toString())) {
                            pair.setValue(new StringLiteralExpr("测试异步流修改AAAAAAAAAA"));
                        }
                    }
                }
            }
        }

        // 将修改后的AST转换回字符串
        String modifiedCode = new PrettyPrinter().print(cu);

        // 将字符串写回到文件
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(modifiedCode);
        }

        return MTDD_Service.loadNodeLinkArray("PlusAsyncFlowTestManager", "PlusAsyncFlowTest");
    }
}
